package v1

import (
	"fmt"
	"usplatformserver/global"
	"usplatformserver/internal/service"
	"usplatformserver/pkg/app"
	"usplatformserver/pkg/errcode"

	"github.com/gin-gonic/gin"
)

type AnalysisStatistics struct{}

func NewStatisticsInfo() AnalysisStatistics {
	return AnalysisStatistics{}
}

// @Summer 获取统计指标
// @Produce json
// @Param token header string true "token"
// @Param organType query string true "检查类型"
// @Param beginTime query string false "起始时间"
// @Param endTime query string false "截止时间"
// @Success 200 {object} model.TargetListSwagger "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/analysis/statistics [get]
func (a *AnalysisStatistics) GetStatisticsInfo(c *gin.Context) {
	param := service.AnalysisStatisticsRequest{}
	response := app.NewResponse(c)

	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	fmt.Print("beginTime: ", param.BeginTime, " endTime: ", param.EndTime)

	svc := service.New(c.Request.Context())
	//获取患者列表
	paramPatientList := service.PatientListRequest{}
	paramPatientList.BeginTime = param.BeginTime
	paramPatientList.EndTime = param.EndTime
	patientList, err := svc.ListWithoutTypeAndPager(&paramPatientList)
	if err != nil {
		// 返回错误
		response.ToErrorResponse(errcode.ErrorGetAlgorithmStatListFail)
		global.Logger.Infof("ListWithoutTypeAndPager failed: %v", err)
		return
	}

	if len(patientList) == 0 {
		response.ToResponse(
			gin.H{
				"list":         nil,
				"checkedCount": 0,
			},
		)
		return
	}

	var patientIds string
	for _, v := range patientList {
		if len(patientIds) == 0 {
			patientIds += fmt.Sprintf("%v", v.ID)
		} else {
			patientIds += fmt.Sprintf(",%v", v.ID)
		}
	}
	global.Logger.Infof("GetStatisticsInfo patientIds: %v", patientIds)

	//获取统计指标
	analysisData, checkedCount, err := svc.GetAnalysisStatisticsData(*param.OrganType, patientIds)
	if err != nil {
		response.ToErrorResponse(errcode.ErrorGetAlgorithmStatListFail)
		global.Logger.Infof("GetAnalysisStatisticsData failed: %v", err)
		return
	}

	// 返回数据
	response.ToResponse(
		gin.H{
			"list":         analysisData,
			"checkedCount": checkedCount,
		},
	)
}

// @Summer 导出统计指标
// @Produce json
// @Param token header string true "token"
// @Param beginTime query string false "起始时间"
// @Param endTime query string false "截止时间"
// @Success 200 {object} model.SwaggerSuccess "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/analysis/statistics/export [get]
func (a *AnalysisStatistics) ExportStatisticsInfo(c *gin.Context) {
	param := service.ProductUsageRateRequest{}
	response := app.NewResponse(c)

	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	fmt.Print("beginTime: ", param.BeginTime, " endTime: ", param.EndTime)

	svc := service.New(c.Request.Context())
	//获取患者列表
	paramPatientList := service.PatientListRequest{}
	paramPatientList.BeginTime = param.BeginTime
	paramPatientList.EndTime = param.EndTime
	patientList, err := svc.ListWithoutTypeAndPager(&paramPatientList)
	if err != nil {
		// 返回错误
		response.ToErrorResponse(errcode.ErrorGetAlgorithmStatListFail)
		global.Logger.Infof("ListWithoutTypeAndPager failed: %v", err)
		return
	}

	if len(patientList) == 0 {
		response.ToResponse(
			gin.H{
				"list":         nil,
				"checkedCount": 0,
			},
		)
		return
	}

	var patientIds string
	for _, v := range patientList {
		if len(patientIds) == 0 {
			patientIds += fmt.Sprintf("%v", v.ID)
		} else {
			patientIds += fmt.Sprintf(",%v", v.ID)
		}
	}
	global.Logger.Infof("GetStatisticsInfo patientIds: %v", patientIds)

	fileName, err := svc.ExportAnalysisStatisticsData(patientIds)
	if err != nil {
		// 返回数据
		response.ToResponse(
			gin.H{
				"list":         nil,
				"checkedCount": 0,
			},
		)
		return
	}

	//回复下载文件
	response.ToResponseDownload(fileName)
}

// @Summer 获取检查统计
// @Produce json
// @Param token header string true "token"
// @Param beginTime query string false "起始时间"
// @Param endTime query string false "截止时间"
// @Success 200 {object} model.CheckedCountListSwagger "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/statistics/checked [get]
func (a *AnalysisStatistics) StatisticCheckedCount(c *gin.Context) {
	param := service.ProductUsageRateRequest{}
	response := app.NewResponse(c)

	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	fmt.Print("beginTime: ", param.BeginTime, " endTime: ", param.EndTime)

	svc := service.New(c.Request.Context())

	checkedList, err := svc.StatisticsCheckedCount(param.BeginTime, param.EndTime)

	if err != nil {
		response.ToErrorResponse(errcode.ErrorStatisticsCheckedCount)
		return
	}

	response.ToResponseListWithoutPager(checkedList)
}

// @Summer 导出检查统计数据
// @Produce json
// @Param token header string true "token"
// @Param beginTime query string false "起始时间"
// @Param endTime query string false "截止时间"
// @Success 200 {object} model.SwaggerSuccess "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/statistics/checked/export [post]
func (a *AnalysisStatistics) ExportStatisticCheckedCount(c *gin.Context) {
	param := service.ProductUsageRateRequest{}
	response := app.NewResponse(c)

	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	fmt.Print("beginTime: ", param.BeginTime, " endTime: ", param.EndTime)

	svc := service.New(c.Request.Context())

	//导处检查量
	fileName, err := svc.ExportStatisticsCheckedCount(param.BeginTime, param.EndTime)
	if err != nil {
		response.ToErrorResponse(errcode.ErrorStatisticsCheckedCountExport)
		global.Logger.Infof("ExportStatisticsCheckedCount failed: %v", err)
		return
	}
	//回复下载
	response.ToResponseDownload(fileName)
}

// @Summer 获取统计指标
// @Produce json
// @Param token header string true "token"
// @Param organType query string true "检查类型"
// @Param beginTime query string false "起始时间"
// @Param endTime query string false "截止时间"
// @Success 200 {object} model.TargetInfoExtListSwagger "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/analysis/statistics/checked/heart [get]
func (a *AnalysisStatistics) GetHeartStatisticsInfo(c *gin.Context) {
	param := service.AnalysisStatisticsRequest{}
	response := app.NewResponse(c)

	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	fmt.Println("beginTime: ", param.BeginTime, " endTime: ", param.EndTime)

	svc := service.New(c.Request.Context())

	//获取统计指标
	analysisData, err := svc.GetHeartAnalysisStatisticsData(*param.OrganType, param.BeginTime, param.EndTime)
	if err != nil {
		response.ToErrorResponse(errcode.ErrorGetHeartMeasureStatFail)
		global.Logger.Infof("GetHeartAnalysisStatisticsData failed: %v", err)
		return
	}

	// 返回数据
	response.ToResponse(analysisData)
}
